package lang
{
	import global.Global;
	
	import utils.IObservable;
	import utils.IObserver;
	
	public class LanguageManager implements IObservable
	{
		private var _cn							: CN = new CN();
		private var _en							: EN = new EN();
		
		private var _observers					: Array = [];
		
		private var _currentLanguageEntity		: Language;
		private var _currentLanguage			: int;
		
		public function get currentLanguage():int {
			return _currentLanguage;
		}
		public function set currentLanguage(value:int):void {
			var changed:Boolean = (value != _currentLanguage);
			_currentLanguage = value;
			updateView();
			// 通知所有观察者
			if(changed) {
				for each(var observer:IObserver in _observers) {
					observer.updateObserver(this, _currentLanguage);
				}
			}
		}
		public function get countObservers():int {
			return _observers.length;
		}
		
		public function LanguageManager()
		{
		}
		public function init():void {
			_currentLanguage = int(Global.config.DefaultLanguage.toString());
			updateView();
		}
		private function updateView():void {
			switch(_currentLanguage) {
				case Language.CN:
					_currentLanguageEntity = _cn;
					break;
				case Language.EN:
					_currentLanguageEntity = _en;
					break;
				default:
					_currentLanguageEntity = _en;
					_currentLanguage = Language.EN;
					break;
			}
		}
		
		/**
		 *
		 * 根据输入的KEY获取文字 
		 * @param key 输入的KEY
		 * @return 获取的文字
		 * 
		 */		
		public function getLanguageText(key:String):String {
			if(_currentLanguageEntity == null) return null;
			return (_currentLanguageEntity.dictionary[key] as String);
		}
		public function addObserver(observer:IObserver):void {
			if(_observers.indexOf(observer) < 0) {
				_observers.push(observer);
			}
		}
		public function deleteObserver(observer:IObserver):void {
			var index:int;
			while((index = _observers.indexOf(observer)) >= 0) {
				_observers.splice(index, 1);
			}
		}
		public function clearObservers():void {
			_observers.splice(0, _observers.length);
		}
	}
}